<template>
  <el-upload
    v-if="editMode"
    class="image-uploader"
    :http-request="httpRequestImr"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" v-bind="$attrs" class="avatar" />
    <el-icon v-else v-bind="$attrs" class="image-uploader-icon"><Plus /></el-icon>
  </el-upload>

  <el-image
    v-else
    v-bind="$attrs"
    class="avatar"
    :src="imageUrl"
    :preview-src-list="[imageUrl]"
    fit="cover"
  >
    <template #error>
      <div class="image-slot">
        {{ t('profile.info.noPhoto') }}
      </div>
    </template>
  </el-image>
</template>

<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { useUpload } from '@/components/UploadFile/src/useUpload'

const props = defineProps({
  fileSize: {
    type: Number,
    default: 20
  }
})

const imageUrl = defineModel({
  type: String,
  required: true
})

const editMode = inject('editMode', true)

const message = useMessage()
const { t } = useI18n()

const { httpRequestImr } = useUpload()

const handleAvatarSuccess: UploadProps['onSuccess'] = (res: any) => {
  imageUrl.value = res.data.url
  message.success(t('imrImage.uploadSuccess'))
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 可以上传jpg和png格式
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    message.error(t('imrImage.fileTypeError'))
    return false
  } else if (rawFile.size / 1024 / 1024 > props.fileSize) {
    message.error(t('imrImage.fileSizeError', { size: props.fileSize }))
    return false
  }
  return true
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 120px;
  height: 120px;
  display: block;
  border-radius: 6px;
}

.image-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
  }

  .el-icon.image-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
  }
}

:deep(.image-slot) {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 14px;
}
</style>
